<template>
  <div class="collect_page">
    <!-- 左侧 输入区域 开始 -->
    <div class="left_info">
      <el-form
        ref="form"
        :model="form"
        :rules="formRules"
        label-width="140px"
        size="small"
      >
        <el-form-item label="姓名：" required>
          <el-select
            v-model="form.id"
            class="a_select"
            placeholder="请输入至少两个关键词搜索"
            remote
            :remote-method="getCustomer"
            :loading="loading"
            filterable
            @change="changeCustomer"
          >
            <el-option
              v-for="(item, index) in customerList"
              :key="index"
              :label="`${item.name}/${item.code}`"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约记录：" prop="orderId">
          <el-select
            v-model="form.orderId"
            class="a_select"
            filterable
            @change="getHistory"
          >
            <el-option
              v-for="(item, index) in recordList"
              :key="index"
              :label="`${item.name}`"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="预约医院：" required>
          <span>欧卡多口腔</span>
        </el-form-item>
        <el-form-item label="预约时间：" required>
          <span>2021-10-23 21:12</span>
        </el-form-item> -->
        <el-form-item label="收款类型：" prop="dealType">
          <el-radio-group v-model="form.dealType" @change="changeDealType">
            <!-- <el-radio :label="1" v-if="!status">收尾款</el-radio>
            <el-radio :label="2" v-if="!status">新增成交</el-radio>
            <el-radio :label="3">退款</el-radio> -->
            <template v-if="status != 7">
              <el-radio :label="4">收尾款</el-radio>
              <el-radio :label="5">新增成交</el-radio>
              <el-radio :label="6">退款</el-radio>
            </template>
            <el-radio :label="7" v-if="status == 7">错误金额修正</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="成交项目：" required>
          <span v-if="form.dealType == 4">{{
            dealProjectInfo.dealProjects
          }}</span>
          <el-select
            v-model="form.dealProject"
            multiple
            class="a_select"
            v-if="form.dealType == 5 || form.dealType == 7"
          >
            <el-option
              v-for="(item, index) in projectList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          :label="`${form.dealType == 6 ? '成交金额减少' : '新增成交金额'}：`"
          prop="dealAmount"
        >
          <span v-if="form.dealType == 4">{{ form.dealAmount }}</span>
          <el-input
            v-model.number="form.dealAmount"
            class="a_input"
            v-if="form.dealType != 4"
          ></el-input>
        </el-form-item>

        <template v-if="form.dealType == 4">
          <!-- <el-form-item label="成交项目：" required>
            <span>{{dealProjectInfo.dealProjects}}</span>
          </el-form-item> -->
          <!-- <el-form-item label="新增成交金额：" required>
            <span>{{form.dealAmount}}</span>
          </el-form-item> -->
        </template>
        <template v-if="form.dealType == 6">
          <!-- <el-form-item label="成交项目：" required>
            <span>{{dealProjectInfo.dealProjects}}</span>
          </el-form-item> -->
          <!-- <el-form-item label="成交金额减少：" prop="dealAmount">
            <el-input v-model.number="form.dealAmount" class="a_input"></el-input>
          </el-form-item> -->
        </template>
        <!-- <template v-if="form.dealType != 5 && form.dealType != 7">
          <el-form-item label="成交项目：" required>
            <span>{{dealProjectInfo.dealProjects}}</span>
          </el-form-item>
          <el-form-item label="新增成交金额：" required>
            <span>{{form.dealAmount}}</span>
          </el-form-item>
        </template> -->
        <template v-if="form.dealType == 5 || form.dealType == 7">
          <!-- <el-form-item label="成交项目：" prop="dealProject">
            <el-select v-model="form.dealProject" multiple class="a_select">
              <el-option v-for="(item,index) in projectList" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="新增成交金额：" prop="dealAmount">
            <el-input v-model.number="form.dealAmount" class="a_input"></el-input>
          </el-form-item> -->
        </template>
        <el-form-item
          :label="`${form.dealType == 6 ? '退款金额减少' : '收款金额'}：`"
          prop="collectMoney"
        >
          <el-input
            v-model.number="form.collectMoney"
            class="a_input"
          ></el-input>
        </el-form-item>
        <el-form-item label="收款时间：" prop="collectTime">
          <el-date-picker
            v-model="form.collectTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有无潜在成交：" prop="potentialDeal">
          <el-radio-group v-model="form.potentialDeal">
            <el-radio :label="0">无</el-radio>
            <el-radio :label="1">有</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            type="textarea"
            v-model="form.remark"
            class="a_input"
            resize="none"
            rows="5"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="saveInfo"
            >保存</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 左侧 输入区域 end -->

    <!-- 右侧历史 开始 -->
    <div class="right_record">
      <div class="title">{{ customerInfo.name }}的历史收款记录</div>
      <el-scrollbar class="list_box">
        <div class="cell_box" v-for="(item, index) in historyList" :key="index">
          <div class="cell">
            <div class="name required">收款时间：</div>
            <div class="txt">{{ item.collectTime }}</div>
          </div>
          <div class="cell">
            <div class="name required">收款原因：</div>
            <div class="txt">{{ item.dealType }}</div>
          </div>
          <div class="cell">
            <div class="name required">成交金额：</div>
            <div class="txt">{{ item.dealAmount }}</div>
          </div>
          <div class="cell">
            <div class="name required">收款金额：</div>
            <div class="txt">{{ item.collectMoney }}</div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <!-- 右侧历史 end -->
  </div>
</template>
<script>
import moment from "moment";
import { deepClone, showToast } from "@/common/util";
import { GETCUSTOMEROPTIONS } from "@/http/customer";
import { GETPROJECTOPTIONS } from "@/http/system";
import { GETORDEROPTIONS, DEALINFOCHANGE, GETDEALHISTORY } from "@/http/deal";
import { Validator } from "@/common/validator";
import { GETDEALS } from "@/http/book";
export default {
  name: "DealCollect",
  props: {
    status: {
      type: [String, Number],
      default: "",
    },
    id: {
      type: [String, Number],
      default: "",
    },
    info: {
      type: Object,
      default: function () {
        return {};
      },
    },
  },
  watch: {
    info: {
      handler: function (n) {
        if (n) {
          console.log(n)
          let _form = deepClone(this.form);
          _form = Object.assign(n);
          console.log(_form)
          this.$set(this,'form',_form)
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      form: { dealType: 4, dealProject: [] },
      pickerOptions: {
        disabledDate: function (e) {
          let n = moment().subtract(7, "days").format("x");
          let m = moment(e).format("x");
          let now = moment().format("x");
          if (m < n) {
            return true;
          }

          if (m > now) {
            return true;
          }
        },
      },
      customerList: [],
      recordList: [],
      projectList: [],
      formRules: {
        orderId: [
          { required: true, message: "请选择预约记录", trigger: "change" },
        ],
        dealType: [
          { required: true, message: "请选择收款类型", trigger: "change" },
        ],
        dealProject: [
          { required: true, message: "请选择成交项目", trigger: "change" },
        ],

        collectMoney: [
          { required: true, message: "请输入收款金额", trigger: "blur" },
        ],
        collectTime: [
          { required: true, message: "请输入收款时间", trigger: "blur" },
        ],
        potentialDeal: [
          { required: true, message: "请选择有无潜在成交", trigger: "change" },
        ],
      },
      loading: false,
      historyList: [],
      customerInfo: {},
      dealProjectInfo: {},
    };
  },
  created() {
    console.log(this.status);
    let _status = this.status || 4
    this.$set(this.form,'dealType',_status)
    //this.form.dealType = this.status || 4;
    this.initRules(_status);
  },
  mounted() {
    let _this = this;
    //this.getCustomer();
    if (_this.id) {
      _this.$set(_this.form, "id", _this.id);
      _this.getCustomer("", _this.id).then(() => {
        _this.changeCustomer(_this.id);
        _this.getBook(_this.id);
      });
    }
    this.getProject();
  },
  methods: {
    // 获取客户列表
    getCustomer(name, id) {
      let _this = this;
      let oParams = {};
      oParams.name = name;

      if ((!name || name.length < 2) && !id) {
        return false;
      }

      if (id) {
        oParams.id = id;
      }

      return new Promise((resolve, reject) => {
        GETCUSTOMEROPTIONS(oParams)
          .then((res) => {
            _this.customerList = res.data || [];
            // if (_this.id) {
            //   _this.$set(_this.form, "id", _this.id);
            //   _this.changeCustomer(_this.id);
            //   _this.getBook(_this.id);
            // }
            resolve(res.data || []);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 查询客户预约信息
    getBook(id) {
      GETORDEROPTIONS({ customerId: id }).then((res) => {
        let list = res.data || [];
        this.recordList = res.data || [];
        if (list[0]) {
          this.$set(this.form, "orderId", list[0].id);

          this.getHistory(list[0].id);
        } else {
          delete this.form.orderId;
          this.historyList = [];
          this.dealProjectInfo = {};
        }
      });
    },

    // 获取所有项目
    getProject() {
      GETPROJECTOPTIONS().then((res) => {
        this.projectList = res.data || [];
      });
    },

    // 保存数据
    saveInfo() {
      let _this = this;

      _this.$refs.form.validate((valid) => {
        if (!valid) {
          _this.$emit("change");
          return false;
        }

        let oParams = deepClone(_this.form);
        //oParams.feedbackId  todo 待定，

        if (oParams.dealProject) {
          oParams.dealProject = oParams.dealProject.toString();
        }

        // 如果是退款，则成交金额减少必须小于等于退款金额减少
        if (
          oParams.dealType == 6 &&
          oParams.dealAmount > oParams.collectMoney
        ) {
          showToast({
            message: "成交金额减少必须小于等于退款金额减少",
          });
          return false;
        }

        // 如果收尾款，校验尾款是否大于成交金额
        // if (
        //   oParams.dealType == 4 &&
        //   Number(oParams.collectMoney) > Number(oParams.dealAmount || 0)
        // ) {
        //   showToast({
        //     message: "尾款金额不能大于成交金额",
        //   });
        //   _this.$emit("change");
        //   return false;
        // }
        delete oParams.id;

        console.log(oParams);
        _this.loading = true;
        DEALINFOCHANGE(oParams)
          .then((res) => {
            _this.loading = false;
            if (res.code == 200) {
              showToast({
                message: "保存成功",
                type: "success",
              });
              _this.$emit("change", { id: "collectDialog" });
            }
          })
          .catch((error) => {
            _this.loading = false;
          });
      });
    },

    // 获取历史收款记录
    getHistory(id) {
      GETDEALHISTORY({ orderId: id }).then((res) => {
        this.historyList = res.data || [];
      });
      this.getDealsProject(id);
    },

    // 监听用户选择
    changeCustomer(id) {
      let o = this.customerList.find((k) => k.id == id);
      console.log(o);
      this.customerInfo = o || {};
      //this.getHistory(id);
      this.getBook(id);
    },

    // 监听切换收款类型
    changeDealType(e) {
      let o = this.formRules.collectMoney;
      let n = this.formRules.dealAmount;
      if (e == 6) {
        o.push({
          pattern: Validator.ISNEGATIVENUMBER,
          message: "退款时，退款金额减少只能为负数",
          trigger: "blur",
        });
        n = [
          { required: true, message: "请输入成交金额减少", trigger: "blur" },
          {
            pattern: Validator.ISNEGATIVENUMBER,
            message: "退款时，成交金额减少只能为负数",
            trigger: "blur",
          },
        ];
      } else {
        o = [{ required: true, message: "请输入收款金额", trigger: "blur" }];
        n = [
          { required: true, message: "请输入成交金额减少", trigger: "blur" },
        ];
      }
      this.$set(this.formRules, "collectMoney", o);
      this.$set(this.formRules, "dealAmount", n);
    },

    // 获取项目
    getDealsProject(id) {
      GETDEALS({ orderId: id }).then((res) => {
        let list = res.data || [];
        this.dealProjectInfo = list[0] ? list[0] : {};
      });
    },

    // 初始化校验规则
    initRules(type) {
      let rules = deepClone(this.formRules);

      let o = rules.collectMoney;
      let n = rules.dealAmount;

      if (type == 4) {
        n = [];
      }

      if (type == 6) {
        o.push({
          pattern: Validator.ISNEGATIVENUMBER,
          message: "退款时，退款金额减少只能为负数",
          trigger: "blur",
        });
        n = [
          { required: true, message: "请输入成交金额减少", trigger: "blur" },
          {
            pattern: Validator.ISNEGATIVENUMBER,
            message: "退款时，成交金额减少只能为负数",
            trigger: "blur",
          },
        ];
      }

      if (type == 5) {
        o = [{ required: true, message: "请输入收款金额", trigger: "blur" }];
        n = [
          { required: true, message: "请输入成交金额减少", trigger: "blur" },
        ];
      }

      this.$set(this.formRules, "collectMoney", o);
      this.$set(this.formRules, "dealAmount", n);
    },
  },
};
</script>
<style lang="scss">
.list_box {
  .el-scrollbar__wrap {
    max-height: 60vh;
    overflow-x: hidden;
  }
}
</style>
<style lang="scss" scoped>
.collect_page {
  display: flex;
  .left_info {
    flex: 1.5;
    padding-right: 20px;
    .a_input,
    .a_select {
      width: 80%;
    }
  }
  .right_record {
    flex: 1;
    position: relative;
    padding: 0 0 0 20px;
    .title {
      font-size: 14px;
      font-weight: bold;
      margin-bottom: 16px;
    }
    .list_box {
      .cell_box {
        position: relative;
        padding: 10px 0;
        .cell {
          display: flex;
          align-items: center;
          line-height: 2;
          .name {
            padding: 0 0 0 6px;
          }
          .required {
            position: relative;
          }
          .required:after {
            position: absolute;
            display: block;
            content: "*";
            color: #f00;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
          }
        }
      }
      .cell_box:after {
        display: block;
        content: "";
        height: 1px;
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background: #eee;
      }
      .cell_box:last-child:after {
        display: none;
      }
    }
  }
  .right_record:after {
    display: block;
    position: absolute;
    content: "";
    width: 1px;
    top: 0;
    bottom: 0;
    left: 0;
    background: #eee;
  }
}
</style>